package com.bsc.rtc.lib.libraries.RetrofitNet.api;


import android.content.res.AssetManager;
import android.util.Log;


import com.bsc.rtc.lib.libraries.Constant;
import com.bsc.rtc.lib.libraries.MyApplication;
import com.bsc.rtc.lib.libraries.RetrofitNet.transport.FileResponseBody;
import com.bsc.rtc.lib.libraries.RetrofitNet.transport.RetrofitCallback;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;

import retrofit2.converter.gson.GsonConverterFactory;

/**
 * author: robin
 * date:    2018/10/9
 * version: v1.0
 * description: 网络请求工具获取类
 */

@Singleton
public class APIServiceCreator {

    private static APIService apiService;
    private static OkHttpClient okHttpClient = null;

    @Inject
    public APIServiceCreator() {
        setupOkHttp();
        setupRetrofit();
    }

    private void setupOkHttp() {
        //************************证书配置************************
        HttpsUtils.SSLParams sslParams = null;
        try {
            AssetManager am = MyApplication.getInstance().getAssets();
            InputStream ins = am.open("log.cer");
            sslParams = HttpsUtils.getSslSocketFactory(null, null, new InputStream[]{ins});
        } catch (IOException e) {
            Log.e("http", "okhttp create failed err");
            Log.e("http", "err " + e.getLocalizedMessage());
        }

        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        if (s.equals("119.3.8.171")
                        ) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                });
        if (Constant.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            builder.addInterceptor(loggingInterceptor);
        }
        //设置缓存
        // Cache cache = new Cache(new File(Constants.PATH_CACHE), 1024 * 1024 * 100);
        okHttpClient = builder
                //.cache(cache)
                .readTimeout(100, TimeUnit.SECONDS)
                .writeTimeout(100, TimeUnit.SECONDS)
                .connectTimeout(100, TimeUnit.SECONDS) //设置超时
                .retryOnConnectionFailure(true) //错误重连
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                                .addHeader("Connection", "keep-alive")
                                .addHeader("Accept", "*/*")
                                .addHeader("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXNzd29yZCI6IjEyMzQ1NiIsImV4cCI6MTU2OTk5NjczOCwidXNlcm5hbWUiOiIxNTIxMDExMTAxNCJ9.4rrei9jF9ksAvmWI_0-qb1EDGxvz0eqycqJpcWHi-C0")
                                .build();
                        Log.i("http", request.toString());
                        return chain.proceed(request);


                    }
                })
                .build();

    }

    private void setupRetrofit() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_RUL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = retrofit.create(APIService.class);
    }

    private <T> T getService(Class<T> c){
        Retrofit retrofit = new Retrofit.Builder().build();
       return retrofit.create(c);
    }
    public APIService getRequester() {
        return apiService;
    }

    public OkHttpClient getAPIClient() {

        if (okHttpClient == null) {
            setupOkHttp();
            setupRetrofit();
        }
        return okHttpClient;
    }

}
